package top.tenebrous.yzl.auth;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.tenebrous.yzl.model.dto.TokenDto;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Project: grpc-demo
 * @Package: com.tenebrous.grpc.auth
 * @Author: zhangya
 * @CreateTime: 2023-05-29  17:57
 * @Version: 1.0.0
 */
@Service
public class AuthTokenGenerator {

    String randomStr = "abcdefghijklmnopqrstuvwsyz0123456789ABCDEFGHIJKLMNOPQRSTUVWSYZ-=_+><~";

    private final Map<String, String> tokenMap = new ConcurrentHashMap<>();
    /**
     * @description:
     * 生成唯一token
     *
     * @author: zhangya
     * @date: 2023/6/3 22:57
     * @param:
     * @return:
     **/
    public String generateToken(String instanceId){
        //生成唯一不重复的字符串
        String random = RandomStringUtils.random(100, randomStr);
        String random1 = RandomStringUtils.random(100, randomStr);
        String random2 = RandomStringUtils.random(100, randomStr);
        String token = random + "." + random1 + "." + random2 + "==";
        tokenMap.put(instanceId, token);
        return token;
    }

    public TokenDto checkToken(String instanceId, String token) {
        String originToken = tokenMap.get(instanceId);
        if (StringUtils.isEmpty(originToken)) {
            return  new TokenDto(false, "this instance not register");
        }
        if (!originToken.equals(token)) {
            return new TokenDto(false, "token not equals");
        }
        return new TokenDto(true, "success");
    }

}
